// 兔子照片生成器前端逻辑

const generateBtn = document.getElementById('generate-btn');
const imageContainer = document.getElementById('image-container');
const loading = document.getElementById('loading');

// API端点
const API_ENDPOINT = '/api/random-rabbit';

// 生成兔子照片
async function generateRabbitPhoto() {
    try {
        // 显示加载状态
        generateBtn.disabled = true;
        loading.classList.remove('hidden');
        
        // 调用API
        const response = await fetch(API_ENDPOINT);
        const data = await response.json();
        
        if (data.success) {
            displayRabbitImage(data.imageUrl);
        } else {
            throw new Error('获取图片失败');
        }
    } catch (error) {
        console.error('Error:', error);
        displayError();
    } finally {
        // 隐藏加载状态
        generateBtn.disabled = false;
        loading.classList.add('hidden');
    }
}

// 显示兔子图片
function displayRabbitImage(imageUrl) {
    const img = document.createElement('img');
    img.src = imageUrl;
    img.alt = '可爱的兔子';
    img.className = 'w-full h-96 object-cover rounded-lg shadow-lg';
    
    // 添加加载动画
    img.style.opacity = '0';
    img.style.transition = 'opacity 0.5s ease-in-out';
    
    // 清空容器并添加新图片
    imageContainer.innerHTML = '';
    imageContainer.appendChild(img);
    
    // 淡入效果
    setTimeout(() => {
        img.style.opacity = '1';
    }, 100);
}

// 显示错误信息
function displayError() {
    imageContainer.innerHTML = `
        <div class="w-full h-96 bg-red-50 rounded-lg flex items-center justify-center">
            <div class="text-center">
                <i class="fas fa-exclamation-triangle text-4xl text-red-400 mb-4"></i>
                <p class="text-red-600">获取兔子图片失败，请重试</p>
            </div>
        </div>
    `;
}

// 事件监听
generateBtn.addEventListener('click', generateRabbitPhoto);

// 页面加载时生成第一张图片
document.addEventListener('DOMContentLoaded', () => {
    // 延迟1秒自动加载第一张图片
    setTimeout(generateRabbitPhoto, 1000);
});

// 键盘快捷键
document.addEventListener('keydown', (e) => {
    if (e.code === 'Space' && !generateBtn.disabled) {
        e.preventDefault();
        generateRabbitPhoto();
    }
});

// 添加键盘提示
document.addEventListener('DOMContentLoaded', () => {
    const hint = document.createElement('div');
    hint.className = 'text-center text-sm text-gray-500 mt-4';
    hint.innerHTML = '<i class="fas fa-keyboard mr-1"></i> 按空格键快速生成';
    document.querySelector('.rabbit-card').appendChild(hint);
});
